package com.mikao.service.impl;

import com.mikao.dao.GoodsDao;
import com.mikao.dto.bo.DiscountForm;
import com.mikao.dto.bo.ReqDataTableDto;
import com.mikao.dto.vo.DiscountDto;
import com.mikao.dto.vo.RspDataTableDto;
import com.mikao.entity.Goods;
import com.mikao.service.DiscountService;
import org.springframework.beans.BeanUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.persistence.criteria.Predicate;
import java.util.ArrayList;
import java.util.List;

/**
 * @author kenny
 */
@Service
public class DiscountServiceImpl implements DiscountService {

    private GoodsDao goodsDao;

    public DiscountServiceImpl(GoodsDao goodsDao) {
        this.goodsDao = goodsDao;
    }

    @Override
    public RspDataTableDto<DiscountDto> discountList(ReqDataTableDto reqDataTableDto, String name) {
        List<DiscountDto> dtos = new ArrayList<>();
        DiscountDto dto;

        PageRequest pageRequest = new PageRequest(reqDataTableDto.getPage(), reqDataTableDto.getLength(),
                new Sort(Sort.Direction.DESC, "createTime"));
        Page<Goods> page = goodsDao.findAll((root, criteriaQuery, criteriaBuilder) -> {
            List<Predicate> predicates = new ArrayList<>();
            if (StringUtils.hasText(name)) {
                Predicate p1 = criteriaBuilder.like(root.get("name"), "%" + name + "%");
                predicates.add(p1);
            }
            Predicate p2 = criteriaBuilder.equal(root.get("isDiscount").as(Boolean.class), true);
            predicates.add(p2);
            return criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()]));
        }, pageRequest);

        for (Goods goods : page.getContent()) {
            dto = new DiscountDto();
            BeanUtils.copyProperties(goods, dto);
            dto.setAfPrice(Float.valueOf(String.format("%.2f", Integer.valueOf(goods.getPrice()) * goods.getDiscount())));
            dtos.add(dto);
        }
        return new RspDataTableDto<>(reqDataTableDto.getDraw(), page.getTotalElements(), dtos);
    }

    @Override
    public void addDiscount(DiscountForm discountForm) {
        Goods goods = goodsDao.findOne(discountForm.getId());
        BeanUtils.copyProperties(discountForm, goods);
        goods.setIsDiscount(true);
        goodsDao.saveAndFlush(goods);
    }

    @Override
    public void deleteDiscount(Long id) {
        Goods goods = goodsDao.findOne(id);
        goods.setIsDiscount(false);
        goods.setDiscount(null);
        goods.setEndTime(null);
        goodsDao.saveAndFlush(goods);
    }

    @Override
    public List<Goods> goodsList(String name) {
        System.out.println(name);
        return goodsDao.findAllByTypeLike(name);
    }

}
